
var netUtil = require('/../../utils/netUtil.js');
var util = require('/../../utils/util.js');
var app = getApp();
var queryBatchNumArray = 0;
Page({
  data:{
 		voucherId : null,
 		getOrderDetail : null,
 		getOrderDetailItemSize : null,
 		
 		batchNumArray : [],
 		showBatchNumObjectArray : null,
 		showBatchNumIndex : null,       //需要选择批次的记录下标
 		isShowChooseBatchNum : false,
 		chooseBatchNumHint : '点击选择批次!',
 		
 		typeAndGoodArray : [[] , []],       //用户显示 选择品种picker的属性
		respTypeAndGoodArray : null,
		logisticsCompanyArray : getApp().globalData.logisticsCompanyArray,
		
		customerAddressList : [],
 		selectAddressCode : null,
 		selectAddressName : null,
 		selectReceiver : null,
 		selectPhoneNum : null,
 		isShowChooseAddress : false
		
  },
  onLoad:function(options){
  	
  	var that = this;
  	
  	//提查单订单号
  	var voucherId = options.voucherId;
  	
  	if(voucherId != undefined && voucherId != null) {
  		this.setData({
  			voucherId : voucherId
  		});
  	}
  	
  	app.getUserOpedId(that.getAllTypeAndGoods);
  	
  	app.getUserOpedId(that.queryGetOrderDetailArray);
  	
  	app.getUserOpedId(that.queryCustomerAddressList);
  
  },
  onReady:function(){
  
  },
  onShow:function(){
    
    // 页面显示
  },
  onHide:function(){
  	queryBatchNumArray = 0;
    // 页面隐藏
  },

  onUnload:function(){
  	queryBatchNumArray = 0;
    // 页面关闭

  },
  
  bindSelectAddressChange : function(e) {
  	
  	this.setData({
  		isShowChooseBatchNum : false,
  		isShowChooseAddress : true, 	
  	});
  	
  	/*var value = e.detail.value;
  	var addressObj = this.data.customerAddressList[value];
  	this.setData({
  		selectAddressCode : addressObj.code,
  		selectAddressName : addressObj.address
  	});*/
  },
  
  selectAddress : function(e) {
  	var arrayIndex = e.currentTarget.dataset.arrayindex;
  	var addressObj = this.data.customerAddressList[arrayIndex];
  	this.setData({
  		selectAddressCode : addressObj.code,
  		selectAddressName : addressObj.address,
  		selectReceiver : addressObj.receiver,
  		selectPhoneNum : addressObj.phoneNum,
  		isShowChooseBatchNum : false,
  		isShowChooseAddress : false, 	
  	});
  },
  
    //查询用户收货地址
  queryCustomerAddressList : function() {
  	var that = this;
  	
  	app.getUserOpedId(function() {
  		
  		var params = {
  			method : 'wechat.wisen.address.userInfo.query',
  			openId : app.globalData.userInfo.openid
  		}
  		
  		netUtil.buildRequest(that,'/wisen/api/wechat/ret',params,{
				
				onPre: function() {
					netUtil.showLoadingDialog(that);
				},
				
				onSuccess: function(resp) {
					console.log(resp);
					
					netUtil.hideLoadingDialog(that);
					
					if(resp.ret == app.globalData.respSuccessCode) {
										
						var customerAddressList = resp.data;
						that.setData({
							customerAddressList : customerAddressList
						});
						
 					} else {
						if(resp.message != undefined && resp.message != null && resp.message != '') {
 							netUtil.showAlertDialog("提示", resp.message, false, "确定", null, null);
 						} else {
 							netUtil.showAlertDialog("提示", "网络请求失败", false, "确定", null, null);
 						}
					}
					
				},
				
				onError: function(res) {
					console.log("fail");
					netUtil.hideLoadingDialog(that);
					netUtil.showAlertDialog("提示", msgCanShow, false, "确定", null, null);
				}
				
			}).send();
  		
  	});
  },
  
  queryBatchNumArrayByGetOrderDetail : function() {
  
  	var that = this;
  	
  	if(queryBatchNumArray + 1 <= that.data.getOrderDetail.outItemsVOs.length) {
  		var outItemsVO = that.data.getOrderDetail.outItemsVOs[queryBatchNumArray];
  			var params = {
  					method : 'wechat.wisen.whbalance.batch.query',
  					openId : app.globalData.userInfo.openid,
  					data : {
  						goodsId : outItemsVO.goodsId
  					}		
 				};
 				
 					 	//选择商品后，发送请求到后台查询批次号，然后设置数据 setData
  		          netUtil.buildRequest(that,'/wisen/api/wechat/ret',params,{
			          	
			          	onPre: function() {
			          		
			          	},
			          	
			          	onSuccess: function(resp) {
			          	
			          		/*{"data":[{"productionBatchNo":"2018-06-06"},{"productionBatchNo":"2018-07-03"},{"productionBatchNo":"2018-07-04"}],"ret":0}*/
    								 
			          		if(resp.ret == app.globalData.respSuccessCode) {
			          							
			          				var respBatchNumArray = resp.data;
			          				
			          				that.data.batchNumArray[queryBatchNumArray] = respBatchNumArray;
			          				
			          				that.setData({
			          					batchNumArray : that.data.batchNumArray						
			          				});
			          				
			          				queryBatchNumArray = queryBatchNumArray + 1;
			          				
			          				that.queryBatchNumArrayByGetOrderDetail();
			          			
 			          		} else {
			          			if(resp.message != undefined && resp.message != null && resp.message != '') {
 			          				netUtil.showAlertDialog("提示", resp.message, false, "确定", null, null);
 			          			} else {
 			          				netUtil.showAlertDialog("提示", "网络请求失败", false, "确定", null, null);
 			          			}
			          		}
			          		
			          	},
			          	
			          	onError: function(res) {
			          		console.log("fail");
			          		netUtil.hideLoadingDialog(that);
			          		netUtil.showAlertDialog("提示", msgCanShow, false, "确定", null, null);
			          	},
			          	
			          	onEnd:function() {
			          		
			          	}
			          	
			          }).send();
 				
  	}
  	
  },
  
  bindLogisticsCompanyChange : function(e) {
  	var value = e.detail.value;
  	var logisticsCompany = this.data.logisticsCompanyArray[value].logisticsCompany;
  	this.data.getOrderDetail.logisticsCompany = logisticsCompany;
  	this.setData({
  		getOrderDetail : this.data.getOrderDetail
  	});
  },
  
  queryGetOrderDetailArray : function() {
  	var that = this;
  	var params = {
  		method : 'wechat.wisen.out.outItems.query',
  		openId : app.globalData.userInfo.openid,
  		data : {
  			voucherId : that.data.voucherId
  		}
  	};
  	
  	netUtil.buildRequest(that,'/wisen/api/wechat/ret',params,{
  		onPre: function() {
				netUtil.showLoadingDialog(that);
			},
			onSuccess : function(resp) {
			 	netUtil.hideLoadingDialog(that);
			
			//如果请求成功
				if(resp.ret == app.globalData.respSuccessCode) {
					
					var getOrderDetail = resp.data;
					
					for(var i=0;i<getOrderDetail.outItemsVOs.length;i++) {
						var outItemsVO = getOrderDetail.outItemsVOs[i];
						outItemsVO.batchNum = outItemsVO.productionBatchNo;
					}
					
					that.setData({
						getOrderDetail : getOrderDetail,
						getOrderDetailItemSize : getOrderDetail.outItemsVOs.length
					});
						
					that.queryBatchNumArrayByGetOrderDetail();
					
				} else {
						
						if(resp.message != undefined && resp.message != null && resp.message != '') {
 							netUtil.showAlertDialog("提示", resp.message, false, "确定", null, null);
 						} else {
 							netUtil.showAlertDialog("提示", "网络请求失败", false, "确定", null, null);
 						}
				}				
			},
			onError: function(msgCanShow, code, hiddenMsg) {
        console.log("fail");
				netUtil.hideLoadingDialog(that);
				netUtil.showAlertDialog("提示", msgCanShow, false, "确定", null, null);
			}
  		
  	}).send();
  	
  },
  
      //列值改变事件
  bindTypeAndGoodsColumnChange : function(e) {
  	
  	var column = e.detail.column;
  	var value = e.detail.value;
  
  	//如果改变第一列
  	if(column == 0) {
  		this.data.typeAndGoodArray[1] = this.data.respTypeAndGoodArray[1][value];
  		this.setData({
  			typeAndGoodArray : this.data.typeAndGoodArray
  		});
  	}
  },
  
    //列值确定事件
  bindTypeAndGoodsChange :function(e) {
	
		var that = this;
  	var value = e.detail.value;
 
  	//由于小程序的bug，第二列动态切换后，如果选择切换后默认的第一个，数据的第二个元素返回 null
  	for(var i=0;i<value.length;i++) {
  		var columnValue = value[i];
  		if(columnValue == null || columnValue == undefined) {
  			value[i] = 0;
  		}
  	}
  	
  	var arrayIndex = e.currentTarget.dataset.initemsindex;
  	var selectGoddIndex = value[1];
   	
  	//1.设置数据对应下标的值
  	var selectedGoodObj = that.data.typeAndGoodArray[1][selectGoddIndex];
  	that.data.getOrderDetail.outItemsVOs[arrayIndex].goodsId = selectedGoodObj.goodsId;
  	that.data.getOrderDetail.outItemsVOs[arrayIndex].goodsName = selectedGoodObj.goodsName;
  	
  	var selectGoodsId = selectedGoodObj.goodsId;
  	var selectGoodsName = selectedGoodObj.goodsName;
  	
  	var params = {
  		method : 'wechat.wisen.whbalance.balance.query',
  		openId : app.globalData.userInfo.openid,
  		data : {
  			goodsName : selectGoodsName
  		}
  		
  	}
  	
  	//选择商品后，发送请求到后台查询批次号，然后设置数据 setData
  		netUtil.buildRequest(that,'/wisen/api/wechat/ret',params,{
				
				onPre: function() {
					netUtil.showLoadingDialog(that);
				},
				
				onSuccess: function(resp) {
					
					/*{"data":[{"productionBatchNo":"2018-06-06"},{"productionBatchNo":"2018-07-03"},{"productionBatchNo":"2018-07-04"}],"ret":0}*/
					
					netUtil.hideLoadingDialog(that);
					
					if(resp.ret == app.globalData.respSuccessCode) {
										
							var respBatchNumArray = resp.data;
							that.data.batchNumArray[arrayIndex] = respBatchNumArray;
							
							that.setData({
								batchNumArray : that.data.batchNumArray						
							});
						
 					} else {
						if(resp.message != undefined && resp.message != null && resp.message != '') {
 							netUtil.showAlertDialog("提示", resp.message, false, "确定", null, null);
 						} else {
 							netUtil.showAlertDialog("提示", "网络请求失败", false, "确定", null, null);
 						}
					}
					
				},
				
				onError: function(res) {
					console.log("fail");
					netUtil.hideLoadingDialog(that);
					netUtil.showAlertDialog("提示", msgCanShow, false, "确定", null, null);
				},
				
				onEnd:function() {
					that.setData({
						getOrderDetail : that.data.getOrderDetail
					});
				}
				
			}).send();
  	
  },
  
  addGetTeaItem : function(e) {
  	
  	var that = this;
  	
  	var outItems = that.data.getOrderDetail.outItemsVOs;
  	
  	//如果有新增或者减少记录，就取最后一条记录出来，发送数据到后台查询 库存是否足够
  	if(outItems != null && outItems.length != that.data.getOrderDetailItemSize) {
  		var checkItem = outItems[outItems.length - 1];
  		
  		if(checkItem.goodsId != null && checkItem.goodsId != '' && (checkItem.unitQuantity != 0 || checkItem.packageQuantity != 0) 
  			&& checkItem.productionBatchNo != null && checkItem.productionBatchNo != '') {
  			 		
  			 		checkItem.batchNum = checkItem.productionBatchNo;
  			 		//发送请求去后台检查库存
  			 		var params = {
  						method : 'wechat.wisen.whbalance.num.check',
  						openId : app.globalData.userInfo.openid,
  						data : {
  							outItems : [checkItem]
  						}
  					};
  										
  		      netUtil.buildRequest(that,'/wisen/api/wechat/ret',params,{
			      	
			      	onPre: function() {
			      		netUtil.showLoadingDialog(that);
			      	},
			      	
			      	onSuccess: function(resp) {
			      		
			      		netUtil.hideLoadingDialog(that);
			      		
			      		if(resp.ret == app.globalData.respSuccessCode) {
			      				var teaItem = {
			     						 	goodsId : '',
			      						goodsName : '',
			      						unitQuantity : 0,
			      						packageQuantity :0,
			      						batchNum : ''
			     					};
			     					that.data.batchNumArray.push([])
			     					that.data.getOrderDetail.outItemsVOs.push(teaItem);
			      				that.setData({
			      					getOrderDetail : that.data.getOrderDetail,
			      					batchNumArray : that.data.batchNumArray
			      				});				
			      			
 			      		} else {
			      			if(resp.message != undefined && resp.message != null && resp.message != '') {
 			      				netUtil.showAlertDialog("提示", resp.message, false, "确定", null, null);
 			      			} else {
 			      				netUtil.showAlertDialog("提示", "网络请求失败", false, "确定", null, null);
 			      			}
			      		}
			      		
			      	},
			      	
			      	onError: function(res) {
			      		console.log("fail");
			      		netUtil.hideLoadingDialog(that);
			      		netUtil.showAlertDialog("提示", msgCanShow, false, "确定", null, null);
			      	}
			      	
			      }).send();
  			 				 		
  			 } else {
  			 		var teaItem = {
			      	goodsId : '',
			      	goodsName : '',
			      	unitQuantity : 0,
			      	packageQuantity :0,
			      	batchNum : ''
			      };
			      this.data.batchNumArray.push([])
			      this.data.getOrderDetail.outItemsVOs.push(teaItem);
			      this.setData({
			      	getOrderDetail : this.data.getOrderDetail,
			      	batchNumArray : this.data.batchNumArray
			      });
  			 }
  		
  	} else {              //如果没有新增或者减少记录，就把所有数据发去后台检验
  		 		
  //		var checkItem = outItems[outItems.length - 1];
  		
  		var checkItemArray = [];
  		
  		for(var i=0;i<outItems.length;i++) {
  			var checkItem = outItems[i];
  			if(checkItem.goodsId != null && checkItem.goodsId != '' && (checkItem.unitQuantity != 0 || checkItem.packageQuantity != 0) 
  					&& checkItem.productionBatchNo != null && checkItem.productionBatchNo != '') {
  			 	
  			 	checkItemArray.push(checkItem);
  			 	
  			 }
  		}
  		
  		if(checkItemArray.length != null && checkItemArray.length > 0) {
  			 		
  			 		checkItem.batchNum = checkItem.productionBatchNo;
  			 		//发送请求去后台检查库存
  			 		var params = {
  						method : 'wechat.wisen.whbalance.num.check',
  						openId : app.globalData.userInfo.openid,
  						data : {
  							outItems : checkItemArray
  						}
  					};
  										
  		      netUtil.buildRequest(that,'/wisen/api/wechat/ret',params,{
			      	
			      	onPre: function() {
			      		netUtil.showLoadingDialog(that);
			      	},
			      	
			      	onSuccess: function(resp) {
			      		
			      		netUtil.hideLoadingDialog(that);
			      		
			      		if(resp.ret == app.globalData.respSuccessCode) {
			      				var teaItem = {
			     						 	goodsId : '',
			      						goodsName : '',
			      						unitQuantity : 0,
			      						packageQuantity :0,
			      						batchNum : ''
			     					};
			     					that.data.batchNumArray.push([])
			     					that.data.getOrderDetail.outItemsVOs.push(teaItem);
			      				that.setData({
			      					getOrderDetail : that.data.getOrderDetail,
			      					batchNumArray : that.data.batchNumArray
			      				});				
			      			
 			      		} else {
			      			if(resp.message != undefined && resp.message != null && resp.message != '') {
 			      				netUtil.showAlertDialog("提示", resp.message, false, "确定", null, null);
 			      			} else {
 			      				netUtil.showAlertDialog("提示", "网络请求失败", false, "确定", null, null);
 			      			}
			      		}
			      		
			      	},
			      	
			      	onError: function(res) {
			      		console.log("fail");
			      		netUtil.hideLoadingDialog(that);
			      		netUtil.showAlertDialog("提示", msgCanShow, false, "确定", null, null);
			      	}
			      	
			      }).send();
  			 				 		
  			 } else {
  			 		var teaItem = {
			      	goodsId : '',
			      	goodsName : '',
			      	unitQuantity : 0,
			      	packageQuantity :0,
			      	batchNum : ''
			      };
			      this.data.batchNumArray.push([])
			      this.data.getOrderDetail.outItemsVOs.push(teaItem);
			      this.setData({
			      	getOrderDetail : this.data.getOrderDetail,
			      	batchNumArray : this.data.batchNumArray
			      });
  			 }
  			
  		/*	var teaItem = {
					goodsId : '',
					goodsName : '',
					unitQuantity : null,
			    packageQuantity :null,
					batchNum : ''
				};
				this.data.batchNumArray.push([])
				this.data.getOrderDetail.outItemsVOs.push(teaItem);
				this.setData({
					getOrderDetail : this.data.getOrderDetail,
					batchNumArray : this.data.batchNumArray
				});*/
  	}
  	
  },
  
  reduceGetTeaItem : function(e) {
		var initemsindex = e.currentTarget.dataset.initemsindex;
		this.data.getOrderDetail.outItemsVOs.splice(initemsindex,1);
		this.setData({
			getOrderDetail : this.data.getOrderDetail
		})
	},
	
		//提交提茶申请
	submitGetTea : function(e) {
		
		var that = this;
		
		var newOutItems = [];
		
		for(var i=0;i<that.data.getOrderDetail.outItemsVOs.length;i++) {
			
			var checkItem = that.data.getOrderDetail.outItemsVOs[i];
			
			if(checkItem.goodsId != null && checkItem.goodsId != '' && (checkItem.unitQuantity != 0 || checkItem.packageQuantity != 0) && checkItem.batchNum != null && checkItem.batchNum != '') {
  			 	newOutItems.push(checkItem);
  		}
		}
		
		if(newOutItems.length <= 0) {
			netUtil.showAlertDialog("提示", '没有有效的记录', false, "确定", null, null);
			return;
		}
		
		var params = {
  		method : 'wechat.wisen.out.voucher.update',
  		openId : app.globalData.userInfo.openid,
  		data : {
  			outItems : newOutItems,
  			voucherId : that.data.voucherId,
  			logisticsCompany : that.data.getOrderDetail.logisticsCompany,
  			code : that.data.getOrderDetail.selectAddressCode
  		}
 		 };
 		 
 		netUtil.buildRequest(that,'/wisen/api/wechat/ret',params,{
				
				onPre: function() {
					netUtil.showLoadingDialog(that);
				},
				
				onSuccess: function(resp) {
				
					netUtil.hideLoadingDialog(that);
					
					if(resp.ret == app.globalData.respSuccessCode) {
										
						//提茶成功后，跳转到订单页	
							wx.reLaunch({
								url: '/pages/order/order?from=getTea'
							});
						
 					} else {
						if(resp.message != undefined && resp.message != null && resp.message != '') {
 							netUtil.showAlertDialog("提示", resp.message, false, "确定", null, null);
 						} else {
 							netUtil.showAlertDialog("提示", "网络请求失败", false, "确定", null, null);
 						}
					}
					
				},
				
				onError: function(res) {
					console.log("fail");
					netUtil.hideLoadingDialog(that);
					netUtil.showAlertDialog("提示", msgCanShow, false, "确定", null, null);
				}
				
			}).send();
	},
  
    //选择数量
	inputTeaCount : function(e) {
		var initemsindex = e.currentTarget.dataset.initemsindex;
		var packageQuantity = e.detail.value;
		
		this.data.getOrderDetail.outItemsVOs[initemsindex].packageQuantity = packageQuantity;
		
		this.setData({
			getOrderDetail : this.data.getOrderDetail
		});	
	},
	
	//选择散量
	inputUnitQuantity : function(e) {
		var initemsindex = e.currentTarget.dataset.initemsindex;
		var unitQuantity = e.detail.value;
		
		this.data.getOrderDetail.outItemsVOs[initemsindex].unitQuantity = unitQuantity;
		
		this.setData({
			getOrderDetail : this.data.getOrderDetail
		});	
	},
  
   //批次选择确定时间
  bindBatchNumChange : function(e) {
  	//var value = e.detail.value;
  
  	var arrayIndex = e.currentTarget.dataset.initemsindex;
  		
  		//如果没有选择茶品为空
  	if(this.data.getOrderDetail.outItemsVOs[arrayIndex].goodsName == '' || this.data.getOrderDetail.outItemsVOs[arrayIndex].goodsName == null) {
  		netUtil.showAlertDialog("提示", '请先选择茶品', false, "确定", null, null);
  		return;
  	}
  	
  	var showBatchNumObjectArray = this.data.batchNumArray[arrayIndex];
  	
  	var chooseBatchNumHint = '';
  	if(showBatchNumObjectArray == null || showBatchNumObjectArray.length <= 0) {
  			chooseBatchNumHint = '尊敬的茶主：本茶品没有库存';
  	} else {	
  			chooseBatchNumHint = '点击选择批次!';
  	}
  	
  	this.setData({
  		showBatchNumObjectArray : showBatchNumObjectArray,
  		isShowChooseBatchNum : true,
  		isShowChooseAddress : false,
  		showBatchNumIndex : arrayIndex,
  		chooseBatchNumHint : chooseBatchNumHint
  	})
  		
  /*	var batchNumObj = this.data.batchNumArray[arrayIndex][value];
  	var batchNum = batchNumObj.productionBatchNo;
  	
  	this.data.getOrderDetail.outItemsVOs[arrayIndex].productionBatchNo = batchNum;
  	this.data.getOrderDetail.outItemsVOs[arrayIndex].batchNum = batchNum;
  	this.setData({
  		getOrderDetail : this.data.getOrderDetail
  	});*/
  	
  },
  
  chooseBatchNum : function(e) {
  		var productionBatchNo = e.currentTarget.dataset.productionbatchno;
  		this.data.getOrderDetail.outItemsVOs[this.data.showBatchNumIndex].productionBatchNo = productionBatchNo;
 			this.data.getOrderDetail.outItemsVOs[this.data.showBatchNumIndex].batchNum = productionBatchNo;
 			this.setData({
 				getOrderDetail : this.data.getOrderDetail,
 				isShowChooseBatchNum : false
 			})
  },
  
  hideChooseBatchNum : function(e) {
  	this.setData({
 				isShowChooseBatchNum : false
 		})
  },
  
  //查询所有类别和商品
	getAllTypeAndGoods : function() {
		var that = this;
		
		var params = {
  		method : 'wechat.wisen.goods.all.query',
  		openId : app.globalData.userInfo.openid
  	}
		
		netUtil.buildRequest(that,'/wisen/api/wechat/ret',params,{
				
				onPre: function() {
					netUtil.showLoadingDialog(that);
				},
				
				onSuccess: function(resp) {
					console.log(resp);
					
					netUtil.hideLoadingDialog(that);
					
					if(resp.ret == app.globalData.respSuccessCode) {
										
						var data = resp.data;
						
						var typeArray = data[0];
						var goodsArray = data[1];
						
						that.data.typeAndGoodArray[0] = typeArray;
						that.data.typeAndGoodArray[1] = goodsArray[0];
						
						that.setData({
							typeAndGoodArray : that.data.typeAndGoodArray,
							respTypeAndGoodArray : data
						});
						
 					} else {
						if(resp.message != undefined && resp.message != null && resp.message != '') {
 							netUtil.showAlertDialog("提示", resp.message, false, "确定", null, null);
 						} else {
 							netUtil.showAlertDialog("提示", "网络请求失败", false, "确定", null, null);
 						}
					}
					
				},
				
				onError: function(res) {
					console.log("fail");
					netUtil.hideLoadingDialog(that);
					netUtil.showAlertDialog("提示", msgCanShow, false, "确定", null, null);
				}
				
			}).send();
		
	}

})